package com.zlz.server.controller;

import com.zlz.server.annotation.OperateLog;
import com.zlz.server.pojo.Admin;
import com.zlz.server.pojo.RespBean;
import com.zlz.server.reqparam.AdminLoginParam;
import com.zlz.server.service.IAdminService;
import com.zlz.server.enums.OprLevel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * @author: zlz
 * @date: 2021/1/16 21:29
 * @description:
 * @since: JDK1.8
 */
@Api(tags = "LoginController")
@RestController
@RequestMapping("/user")
public class LoginController {
    @Resource
    private IAdminService iAdminService;

    @ApiOperation("登录之后返回token")
    @PostMapping("/login")
    @OperateLog(operationName = "登录", moduleName = "登录/登出", level = OprLevel.LOW)
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest httpServletRequest) {
        return iAdminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword(),
                adminLoginParam.getCode(), httpServletRequest);
    }

    @ApiOperation("获取当前登录用户的信息")
    @PostMapping("/info")
    public RespBean getUserInfo(Principal principal) {
        if (principal == null) {
            return RespBean.success(null, null);
        }
        String username = principal.getName();
        Admin admin = iAdminService.getAdminByUserName(username);
        admin.setPassword(null);
        admin.setRoles(iAdminService.getRolesByAdminId(admin.getId()));
        return RespBean.success(null, admin);
    }


    @ApiOperation("退出登录")
    @PostMapping("/logout")
    @OperateLog(operationName = "登出", moduleName = "登录/登出", level = OprLevel.LOW)
    public RespBean logout() {
        return RespBean.success("注销成功", null);
    }
}
